/*
 *所有关于cw_djlc_wljgwh_view类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*cw_djlc_wljgwh_viewService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Finance.IRepositories;
using System.Collections.Generic;
using VOL.Core.DBManager;
using OfficeOpenXml;
using System.Net;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System;

namespace VOL.Finance.Services
{
    public partial class cw_djlc_wljgwh_viewService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Icw_djlc_wljgwh_viewRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public cw_djlc_wljgwh_viewService(
            Icw_djlc_wljgwh_viewRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        WebResponseContent webResponse = new WebResponseContent();

        public override PageGridData<cw_djlc_wljgwh_view> GetPageData(PageDataOptions options)
        {
            SummaryExpress = (IQueryable<cw_djlc_wljgwh_view> queryable) =>
            {
                return (queryable as IQueryable<cw_djlc_wljgwh_view>).GroupBy(x => 0).Select(x => new
                {
                    //AvgPrice注意大小写和数据库字段大小写一样
                    totalprice = x.Sum(o => o.totalprice),
                    decreaseprice = x.Sum(o => o.decreaseprice),
                    rabateprice = x.Sum(o => o.rabateprice)
                }).FirstOrDefault();

            };
            return base.GetPageData(options);
        }
        public override WebResponseContent Update(SaveModel saveModel)
        {
            WebResponseContent webContent = new WebResponseContent();
            var finalprice = saveModel.MainData.Where(S => S.Key == "finalprice").Select(S => S.Value).ToList().FirstOrDefault();
            var wlzbId = saveModel.MainData.Where(S => S.Key == "cw_djlc_wlzb_id").Select(S => S.Value).First();
            var rebateconditions = saveModel.MainData.Where(S => S.Key == "rebateconditions").Select(S => S.Value).First();
            var jgwhId = saveModel.MainData.Where(S => S.Key == "cw_djlc_jgwh_id").Select(S => S.Value).First();
            var pricereason = saveModel.MainData.Where(S => S.Key == "pricereason").Select(S => S.Value).First();
            var rabateprice = saveModel.MainData.Where(S => S.Key == "rabateprice").Select(S => S.Value).First();
            if ((finalprice != null && finalprice.ToString() != "") && !StringExtension.IsNumber(finalprice.ToString(), 8, 6))
            {
                webContent.Code = "-2";
                return webContent.Error("输入不正确，请重新输入！");
            }
            if ((rabateprice != null && rabateprice.ToString() != "") && !StringExtension.IsNumber(rabateprice.ToString(), 8, 6))
            {
                webContent.Code = "-2";
                return webContent.Error("输入不正确，请重新输入！");
            }
            UpdateOnExecuting = (cw_djlc_wljgwh_view wlzb, object addList, object updateList, List<object> delKeys) =>
            {
                string sql, sql2 = "";
                if (finalprice == null || finalprice.ToString() == "")
                {
                    sql = "update cw_djlc_wlzb set [finalprice] = null ,is_synchronization_status = 0 where cw_djlc_wlzb_id = @wlzbId";
                    DBServerProvider.SqlDapper.ExcuteNonQuery(sql, new { wlzbId });
                }
                else
                {
                    sql = "update cw_djlc_wlzb set [finalprice] = @finalprice ,is_synchronization_status = 0 where cw_djlc_wlzb_id = @wlzbId";
                    DBServerProvider.SqlDapper.ExcuteNonQuery(sql, new { finalprice, wlzbId });
                }
                if (rebateconditions == null)
                {
                    sql2 = "update cw_djlc_jgwh set [rebateconditions] = null where cw_djlc_jgwh_id = @jgwhId";
                    DBServerProvider.SqlDapper.ExcuteNonQuery(sql2, new { jgwhId });
                }
                else
                {
                    sql2 = "update cw_djlc_jgwh set [rebateconditions] = @rebateconditions where cw_djlc_jgwh_id = @jgwhId";
                    DBServerProvider.SqlDapper.ExcuteNonQuery(sql2, new { rebateconditions, jgwhId });
                }
                if (pricereason == null)
                {
                    sql = "update cw_djlc_wlzb set [pricereason] = null where cw_djlc_wlzb_id = @wlzbId";
                    DBServerProvider.SqlDapper.ExcuteNonQuery(sql, new { finalprice, wlzbId });
                }
                else
                {
                    sql = "update cw_djlc_wlzb set [pricereason] = @pricereason where cw_djlc_wlzb_id = @wlzbId";
                    DBServerProvider.SqlDapper.ExcuteNonQuery(sql, new { pricereason, wlzbId });
                }
                if (rabateprice == null || rabateprice.ToString() == "")
                {
                    sql = "update cw_djlc_wlzb set [rabateprice] = null where cw_djlc_wlzb_id = @wlzbId";
                    DBServerProvider.SqlDapper.ExcuteNonQuery(sql, new { wlzbId });
                }
                else
                {
                    sql = "update cw_djlc_wlzb set [rabateprice] = @rabateprice where cw_djlc_wlzb_id = @wlzbId";
                    DBServerProvider.SqlDapper.ExcuteNonQuery(sql, new { rabateprice, wlzbId });
                }
                webContent.Code = "-1";
                return webContent.OK("保存成功！");
            };
            return base.Update(saveModel);
           
        }
        public override WebResponseContent Export(PageDataOptions pageData)
        {
            ExportColumns = x => new { x.bomnumber, x.materialnum, x.componentnum,x.parent_componentnum, x.MTyp, x.description, x.num, 
                                       x.pricesource, x.unitprice, x.totalprice,x.priceeffectivedatestart, x.priceeffectivedateend,
                                       x.finalprice,x.pricereason, x.codename, x.decrease, x.rabate, x.rebateconditions, x.decreaseprice,
                                       x.rabateprice, x.effectivedatestart, x.effectivedateend};
            return base.Export(pageData);
        }
        
        /// <summary>
        /// 导入时针对
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public override WebResponseContent Import(List<IFormFile> files)
        {
            DownLoadTemplateColumns = x => new {
                x.bomnumber,
                x.materialnum,
                x.componentnum,
                x.parent_componentnum,
                x.MTyp,
                x.description,
                x.num,
                x.pricesource,
                x.unitprice,
                x.totalprice,
                x.priceeffectivedatestart,
                x.priceeffectivedateend,
                x.finalprice,
                x.pricereason,
                x.codename,
                x.decrease,
                x.rabate,
                x.rebateconditions,
                x.decreaseprice,
                x.rabateprice,
                x.effectivedatestart,
                x.effectivedateend
            };

            ImportOnExecuting = (List<cw_djlc_wljgwh_view> cw_djlc_wljgwh_view) =>
            {
                int num = 0;
                foreach (var item in cw_djlc_wljgwh_view)
                {
                    string materialnum = item.materialnum;
                    string bomnumber = item.bomnumber;
                    cw_djlc_wlzb wlzb = DBServerProvider.DbContext.Set<cw_djlc_wlzb>().Where(x => x.materialnum == materialnum && x.bomnumber == bomnumber).FirstOrDefault();
                    if (wlzb != null)
                    {
                        if (wlzb.bomtype == 1)
                        {
                            num++;
                            break;
                        }
                        else
                        {
                            int count = DBServerProvider.DbContext.Set<cw_djlc_djzb>().Where(x => x.newmaterialnum == materialnum && x.stepid > 60 && x.newbomnumber == bomnumber).ToList().Count();
                            if (count > 0)
                            {
                                num++;
                                break;
                            }
                        }
                    }
                }
                if (num>0)
                {
                    webResponse.Code = "-1";
                    return webResponse.Error("原始物料和已定过价的物料不能被修改价格！");
                }
                var dapper = DBServerProvider.SqlDapper;
                try
                {
                    dapper.BeginTrans();
                    foreach (var item in cw_djlc_wljgwh_view)
                    {
                        /*cw_djlc_wlzb cw_djlc_wlzb = DBServerProvider.DbContext.Set<cw_djlc_wlzb>().Where(x => x.bomnumber == item.bomnumber && x.materialnum == item.materialnum && x.componentnum == item.componentnum).FirstOrDefault();
                        cw_djlc_wlzb.finalprice = item.finalprice;
                        cw_djlc_wlzb.pricereason = item.pricereason;
                        DBServerProvider.DbContext.Set<cw_djlc_wlzb>().Update(cw_djlc_wlzb);
                        DBServerProvider.DbContext.SaveChanges();*/
                        string sql = "update cw_djlc_wlzb set finalprice = @finalprice , pricereason = @pricereason , is_synchronization_status = 0 where bomnumber = @bomnumber and materialnum = @materialnum and componentnum = @componentnum";
                        
                        var data = dapper.ExcuteNonQuery(sql, new { item.finalprice , item.pricereason , item.bomnumber , item.materialnum, item.componentnum });

                    }

                    dapper.Commit();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    dapper.Rollback();
                    webResponse.Code = "-1";
                    return webResponse.OK("修改失败！");
                }
                
                webResponse.Code = "-1";
                return webResponse.OK("修改成功！");
            };

            return base.Import(files);
        }
    }
}
